package com.liuwei.register;

import com.liuwei.common.URL;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//  记录注册相关接口名使用的URL
public class MapRemoteRegister {

    private static Map<String, List<URL>> map = new HashMap<>();

    // 存储
    public static void regist(String interfaceName, URL url) throws IOException {
        List<URL> list = map.get(interfaceName);
        if(list == null){
            list = new ArrayList<>();
        }
        list.add(url);
        map.put(interfaceName,list);

        saveFile();
    }

    // 拿取
    public static List<URL> get(String interfaceName) throws IOException, ClassNotFoundException {
        map = getFile();
        return map.get(interfaceName);
    }

    // 通过文件实现共享
    private static Map<String,List<URL>> getFile() throws IOException, ClassNotFoundException {
        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\dell\\IdeaProjects\\LiuWeiRPC\\temp.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        return (Map<String, List<URL>>) objectInputStream.readObject();
    }
    private static void saveFile() throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\dell\\IdeaProjects\\LiuWeiRPC\\temp.txt");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(map);
    }
}
